$(function () {
    $("#companyBranchGrid").Grid({
        url: '../org/branch/lists',
        colModel: [
			{label: 'id', name: 'id', index: 'id', key: true, hidden: true},
			{label: '所属公司', name: 'companyName', index: 'companyName', width: 80},
			{label: '门店简称', name: 'name', index: 'name', width: 80},
			{label: '门店全名', name: 'allName', index: 'all_name', width: 80},
			{label: '法人', name: 'legal', index: 'legal', width: 80},
			{label: '联系人', name: 'attn', index: 'attn', width: 80},
			{label: '门店电话', name: 'tel', index: 'tel', width: 80},
			{label: '状态', name: 'status', index: 'status', width: 80,
				formatter: function (value) {
					var result="";
					switch (value) {
						case 0:result='<span class="label label-danger">冻结</span>';break;
						case 1:result='<span class="label label-success">正常</span>';break;
						default:result='<span class="label label-success">正常</span>';break;
					}
					return result;
				}
			}]
    });
    Ajax.request({
	    url: '../isSysUser',
	    contentType: "application/json",
        successCallback: function (r) {
        	vm.isAdmin=r.isAdmin;
        }
	});
});

var vm = new Vue({
	el: '#companyBranch',
	data: {
        showList: true,
        title: null,
        isAdmin:false,
        uploadLicenseList:[],
        uploadIdcardPositiveList:[],
        uploadIdcardReverseList:[],
		orgCompanyBranch: {},
		ruleValidate: {
			name: [
				{required: true, message: '名称不能为空', trigger: 'blur'}
			]
		},
		q: {
		    name: '',legal:'',attn:''
		}
	},
	methods: {
		handleBrandRemove:function(event,name){
			var brandId=name;
			var brandSelectedList=vm.orgCompanyBranch.brandList;
			if(brandSelectedList&&brandSelectedList.length>0){
//				var brandSelected=null;
				for (var i = 0; i < brandSelectedList.length; i++) {
//					brandSelected=brandSelectedList[i];
    				if(brandId==brandSelectedList[i].id){
    					brandSelectedList.splice(i,1);break;
    				}
				}
				vm.orgCompanyBranch.brandList=brandSelectedList;
			}
		},
		selectBrandAll:function(){
			openWindow({
            	type: 2,
                title: "选择车辆品牌",
                area: ['80%', '60%'],
                content: ['../product/carbrandSelect.html'],
                btn: ['确定', '取消'],
                btn1: function (index,layero) {
                	var selectRowList = window[layero.find('iframe')[0]['name']].getSelectedRowsData('#carbrandSelectGrid');
                	if(selectRowList&&selectRowList.length>0){
                		for (var i = 0; i < selectRowList.length; i++) {
                			var addSelected=true;
                			for (var j = 0; j < vm.orgCompanyBranch.brandList.length; j++) {
                				if(selectRowList[i].id==vm.orgCompanyBranch.brandList[j].id){
                					addSelected=false;
                				}
							}
                			if(addSelected){
                				vm.orgCompanyBranch.brandList.push(selectRowList[i]);
                			}
                		}
                	}
                    layer.close(index);
                }
            });
		},
		selectParentCompany:function(){
			if(vm.orgCompanyBranch.id){
				alert('所属公司不能修改!');return;
			}
			openWindow({
            	type: 2,
                title: "选择公司",
                area: ['80%', '60%'],
                content: ['../org/companyinfoSelect.html'],
                btn: ['确定', '取消'],
                btn1: function (index,layero) {
                	var selectRowData = window[layero.find('iframe')[0]['name']].getSelectedRowData('#companyInfoGrid');
                	vm.orgCompanyBranch.companyId=selectRowData.id;
                	vm.orgCompanyBranch.companyName=selectRowData.name;
                    layer.close(index);
                }
            });
		},
		query: function () {
			vm.reload();
		},
		add: function () {
			vm.uploadLicenseList=[];
			vm.uploadIdcardPositiveList=[];
			vm.uploadIdcardReverseList=[];
			vm.showList = false;
			vm.title = "新增";
			vm.orgCompanyBranch = {companyId:'',companyName:'',brandList:[]};
		},
		update: function (event) {
			vm.uploadLicenseList=[];
			vm.uploadIdcardPositiveList=[];
			vm.uploadIdcardReverseList=[];
            var id = getSelectedRow("#companyBranchGrid");
			if (id == null) {
				return;
			}
			vm.showList = false;
            vm.title = "修改";

            vm.getInfo(id);
		},
		saveOrUpdate: function (event) {
            var url = vm.orgCompanyBranch.id == null ? "../org/branch/save" : "../org/branch/update";
            Ajax.request({
			    url: url,
                params: JSON.stringify(vm.orgCompanyBranch),
                type: "POST",
			    contentType: "application/json",
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
			});
		},
		del: function (event) {
            var ids = getSelectedRows("#companyBranchGrid");
			if (ids == null){
				return;
			}

			confirm('确定要删除选中的记录？', function () {
                Ajax.request({
				    url: "../org/branch/delete",
                    params: JSON.stringify(ids),
                    type: "POST",
				    contentType: "application/json",
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
					}
				});
			});
		},
		getInfo: function(id){
            Ajax.request({
                url: "../org/branch/info/"+id,
                async: true,
                successCallback: function (r) {
                    vm.orgCompanyBranch = r.orgCompanyBranch;
                    if(vm.orgCompanyBranch.license){
                    	vm.uploadLicenseList.push({name:vm.orgCompanyBranch.license.substr(vm.orgCompanyBranch.license.lastIndexOf("/")),url:vm.orgCompanyBranch.license,status:'finished'});
                    }
                    if(vm.orgCompanyBranch.idcardPositive){
                    	vm.uploadIdcardPositiveList.push({name:vm.orgCompanyBranch.idcardPositive.substr(vm.orgCompanyBranch.idcardPositive.lastIndexOf("/")),url:vm.orgCompanyBranch.idcardPositive,status:'finished'});
                    }
                    if(vm.orgCompanyBranch.idcardReverse){
                    	vm.uploadIdcardReverseList.push({name:vm.orgCompanyBranch.idcardReverse.substr(vm.orgCompanyBranch.idcardReverse.lastIndexOf("/")),url:vm.orgCompanyBranch.idcardReverse,status:'finished'});
                    }
                }
            });
		},
		reload: function (event) {
			vm.showList = true;
            var page = $("#companyBranchGrid").jqGrid('getGridParam', 'page');
			$("#companyBranchGrid").jqGrid('setGridParam', {
                postData: {'name': vm.q.name,'legal':vm.q.legal,'attn':vm.q.attn},
                page: 1
            }).trigger("reloadGrid");
//            vm.handleReset('formValidate');
		},
        reloadSearch: function() {
            vm.q = {
                name: '',legal:'',attn:''
            };
            vm.reload();
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },
        handleView:function(file){
        	openWindow({
            	type: 2,
                title: "图片显示",
                area: ['80%', '60%'],
                content: [file.url],
                btn: ['确定', '取消'],
                btn1: function (index,layero) {
                    layer.close(index);
                }
            });
        },
        handleRemove:function(type){
        	switch (type) {
				case "license":vm.uploadLicenseList=[];break;
				case "idcardPositive":vm.uploadIdcardPositiveList=[];break;
				case "idcardReverse":vm.uploadIdcardReverseList=[];break;
				default:break;
			}
        },
        handleSuccessLicense:function(res, file){
        	vm.uploadLicenseList.push({name:res.filename,url:res.link+res.filename,status:'finished'});
        	vm.orgCompanyBranch.license=res.link+res.filename;
        },
        handleSuccessIdcardPositive:function(res, file){
        	vm.uploadIdcardPositiveList.push({name:res.filename,url:res.link+res.filename,status:'finished'});
        	vm.orgCompanyBranch.idcardPositive=res.link+res.filename;
        },
        handleSuccessIdcardReverse:function(res, file){
        	vm.uploadIdcardReverseList.push({name:res.filename,url:res.link+res.filename,status:'finished'});
        	vm.orgCompanyBranch.idcardReverse=res.link+res.filename;
        },
        handleImgFormatError:function(file){
        	alert('图片格式错误！支持图片格式为:jpg,png,jpeg!');
        },
        handleImgMaxSize:function(file){
        	alert('图片最大大小为4M!');
        },
        handleLicenseImgBeforeUpload:function(){
        	var check = vm.uploadLicenseList.length < 1;
            if (!check) {
            	alert('首先删除原来的图片!');
            }
            return check;
        },
        handleIdcardPositiveImgBeforeUpload:function(){
        	var check = vm.uploadIdcardPositiveList.length < 1;
        	if (!check) {
        		alert('首先删除原来的图片!');
        	}
        	return check;
        },
        handleIdcardReverseImgBeforeUpload:function(){
        	var check = vm.uploadIdcardReverseList.length < 1;
        	if (!check) {
        		alert('首先删除原来的图片!');
        	}
        	return check;
        }
	}
});